const { json } = require("express")
var share = require("../../share")

var spaceType ="room"

var createOrjoinCmd=spaceType+".createOrjoin"
var leaveCmd=spaceType+".leave"
var otherLeaveCmd=spaceType+".otherLeave"
var otherJoinCmd=spaceType+".otherJoin"
var infoCmd=spaceType+".info"
var fullinfoCmd =spaceType+".fullInfo"

exports.createOrjoin = function (id, data, msg) {
   
    share.GPS_Join(id, spaceType, data.name)
    let space_info  =share.getSpaceByTypeAndName( spaceType,data.name)
    console.log("createOrjoin",space_info,space_info.name)
    var reslut = {
        data: space_info
    }
    share.send_response(id,createOrjoinCmd,reslut)

    reslut = ({    
        data: {
            id:id
        }
    })

    let players = space_info.players
    console.log(otherJoinCmd,players)
    for (let i = 0; i < players.length; i++) {
        if (players[i] != id) 
        {
            share.send_response(players[i],otherJoinCmd, reslut)
        }
    }
}

exports.leave = function (id, data, msg) {
    onCloseLink(id)
    share.GPS_Exit(id)
    let reslut ={
        data: {
            id: id
        }
    }
    share.send_response(id,leaveCmd, reslut)
}

exports.info = function(id,data,msg)
{
    let space_info  =share.getSpaceByTypeAndName(spaceType,data.name)
    console.log(space_info)
    let reslut =null
    if(space_info)
    {
        console.log(infoCmd,space_info,space_info.name)
        reslut ={
            code:200,
            data: {
                players:space_info.players
            }
        }
       
    }
    else
    {
        reslut = {
            code:404,
        }
    }
    share.send_response(id,infoCmd,reslut)
}

exports.fullInfo = function(id,data,msg)
{
    let space_info  =share.getSpace(data.type)
    let result={}
    if(space_info)
    {
        result.code = 200
        result.data={}
        Object.keys(space_info).forEach(key => {  
            console.log(key,space_info[key])
            result.data[key]=space_info[key].players.length
          });       
    }
    else
    {
        reslut = {
            code:404,
        }
    }
    share.send_response(id,fullinfoCmd,result)
}

var onCloseLink = function(id)
{
    let playsers = share.findPlayers(id)
    
    if (playsers != null) {
        let reslut = {id: id};
        console.log(otherLeaveCmd,playsers,reslut)
        for(let i=0;i<playsers.length;i++)
        {
            if(playsers[i]!=id)
            {
                share.send_response(playsers[i],otherLeaveCmd, reslut)
            }
        }
    }
}

eventEmitter.addListener('closeLink', onCloseLink);